using System;
using System.Collections.Generic;
using System.Text;
using Dune.Business.Domain.Users;
using Edge.Common;
using Edge.DAL;
using Edge.Common.Utils;
using Edge.DAL.Managers;
using NHibernate;
using NHibernate.Expression;

namespace Dune.DAL.Managers
{
    class UserPersonManager : AbstractManager<Person, int, User>, IUserPersonManager
    {
        public ICollection<Person> Find(FetchOptions fetchOptions, PersonFilter filter)
        {
            try
            {
                ICriteria criteria = CreateCriteria(fetchOptions);
                AddRestrictions(criteria, filter);
                return criteria.List<Person>();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public int Count(PersonFilter filter)
        {
            ICriteria criteria = CreateCriteria();
            AddRestrictions(criteria, filter);
            criteria.SetProjection(Projections.RowCount());
            return (int)criteria.List()[0];
        }

        private void AddRestrictions(ICriteria criteria, PersonFilter filter)
        {
            if (!StringUtils.IsBlankOrNull(filter.GetText()))
            {
                criteria.Add(Expression.Disjunction()
                                 .Add(Expression.Like("Name", "%" + filter.GetText().Trim() + "%"))
                                 .Add(Expression.Like("History", "%" + filter.GetText().Trim() + "%")));
            }

            if (filter.User != null)
            {
                criteria.Add(Expression.Eq("CreatedBy", filter.User));
            }
          }

    }
}
